import java.util.HashMap;
import java.util.LinkedList;

public class Connect {

    public Node connect1(Node root) {
        if (root == null) return root;
        int curLevel = 1;
        HashMap<Node, Integer> maps = new HashMap<>();
        maps.put(root, 1);
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        Node preNode = root;
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            Integer nodeLevel = maps.get(node);
            if (curLevel != nodeLevel) {
                preNode.next = null;
                curLevel++;
            } else {
                preNode.next = node;
            }
            preNode = node;
            if (node.left != null) {
                maps.put(node.left, curLevel + 1);
                queue.add(node.left);
            }
            if (node.right != null) {
                maps.put(node.right, curLevel + 1);
                queue.add(node.right);
            }
        }
        root.next = null;
        return root;
    }

    public Node connect(Node root) {
        if (root == null) return root;
        process(root);
        return root;
    }

    public void process(Node node) {
        if (node.left == null) return;
        node.left.next = node.right;
        if (node.next != null) {
            node.right.next = node.next.left;
        }
        process(node.left);
        process(node.right);
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node(int val, Node left, Node right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
